import { director, error, Prefab, resources, sys } from "cc";
import { NativeInitDataDto } from "../../native/nativeDataModels/NativeInitDataDto";
import { EnvironmentType, GlobelDataMgr, SceneName } from "../../managers/GlobelDataMgr";
import { LogMgr } from "../../components/LogMgr";
import { LanguageEnum, LanguageMgr } from "../../components/language/LanguageMgr";

/**处理进入游戏前面需要处理完成的事情*/
export default class JoinGameProcessCmd{
    private _progressCallback: (progress: number) => void;
    private _overCallBack: () => void;
    private _sceneNames: Array<string> = [SceneName.hall];
    private _sceneIndex: number = 0;
    public start(progressCallback: (progress: number) => void, overCallBack: () => void):void{
        this._progressCallback = progressCallback;
        this._overCallBack = overCallBack;
       LogMgr.log("开始进入游戏流程");
        if(sys.isNative)
        {
            this.getNativeData();
        }else{
            this.loaderInitConfig();
        }
    }
    private getNativeData():void{
       LogMgr.log("获取native数据");
    }
    private onGetNativeData(data:NativeInitDataDto):void{
        if(data.code=="100")
        {
            GlobelDataMgr.instance.setNativeData(data);
        }
        this.loaderInitConfig();
    }
    private loaderInitConfig():void{
       LogMgr.log("加载语言文件");
       LanguageMgr.instance.setLanguage(LanguageEnum.en).then(()=>{
            this.preloadScene();
       }).catch((err)=>{
            this.preloadScene();
       })
    }
    private preloadScene() {
       LogMgr.log("开始预加载场景");
        if (this._sceneIndex >= this._sceneNames.length) {
           LogMgr.log("场景预加载完毕");
            this.allOver();
            return;
        }
        const sceneName = this._sceneNames[this._sceneIndex];
        director.preloadScene(
            sceneName,
            (completedCount, totalCount, item) => {
                const progress =
                    0.3 + (((completedCount / totalCount) * 0.7) / this._sceneNames.length) * (this._sceneIndex + 1);
                this._progressCallback(progress);
            },
            (err) => {
                if (err) {
                    console.error(`Failed to preload scene ${sceneName}:`, err);
                    return;
                }

                console.log(`Scene ${sceneName} preloaded successfully`);
                this._sceneIndex++;
                this.preloadScene();
            }
        );
    }
    private allOver():void{
        this._overCallBack();
    }
}